package tc.de.krawallmann.extension;

import java.util.Collection;

import tc.de.krawallmann.gravoblocks.score.Highscores;
import tc.de.krawallmann.gravoblocks.score.Score;
import tc.de.krawallmann.persistence.XMLStorage;

/**
 * The Class HighscoresExtension manages highscores
 * 
 * @author KrawallMann
 * @version 1.0
 */
public class HighscoresExtension implements PersistenceExtension {

	/** The scores. */
	private transient Highscores scores;

	/** The scores file. */
	private transient final String scoresFile;

	/**
	 * Instantiates a new HighscoresExtension.
	 * 
	 * @param scoresFile
	 *            the scores file
	 */
	public HighscoresExtension(final String scoresFile) {
		super();
		if (scoresFile == null) {
			throw new IllegalArgumentException("Scores file is null!");
		}
		this.scoresFile = scoresFile;
	}

	/**
	 * Adds the Score.
	 * 
	 * @param score
	 *            the Score
	 * @return true, if successful
	 */
	public boolean addScore(final Score score) {
		return scores.add(score);
	}

	/**
	 * Checks if there is an "equal" Score.
	 * 
	 * @param string
	 * @param score
	 *            the Score to be checked
	 * @return true, if there is such a Score
	 */
	public boolean contains(final String gamemode, final int score) {
		return scores.contains(gamemode, score);
	}

	/**
	 * Gets the Score at the given index.
	 * 
	 * @param index
	 *            the index
	 * @return the Score at the given index
	 */
	public Score getScore(final int index) {
		return scores.getScore(index);
	}

	/*
	 * (non-Javadoc)
	 * @see tc.de.krawallmann.extension.Extension#init()
	 */
	@Override
	public void init() {
		// Not needed!
	}

	/*
	 * (non-Javadoc)
	 * @see tc.de.krawallmann.extension.PersistenceExtension#read()
	 */
	@Override
	public boolean read() {
		try {
			scores = XMLStorage.deserialize(scores, scoresFile);
			return true;
		} catch (final Exception e) {
			scores = new Highscores();
			return false;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see tc.de.krawallmann.extension.PersistenceExtension#store()
	 */
	@Override
	public boolean store() {
		try {
			XMLStorage.store(scores, scoresFile);
			return true;
		} catch (final Exception e) {
			return false;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see tc.de.krawallmann.extension.Extension#update(long)
	 */
	@Override
	public void update(final long delta) {
		// Not needed!
	}

	/**
	 * Returns all Scores
	 * 
	 * @return the collection
	 */
	public Collection<Score> values() {
		return scores;
	}

}
